package com.t2c.tibetantochinese.utils;

import android.app.Activity;

import com.t2c.tibetantochinese.realmModel.Audio;
import com.t2c.tibetantochinese.realmModel.Category;
import com.t2c.tibetantochinese.realmModel.Phrase;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import io.realm.Realm;
import io.realm.RealmQuery;
import io.realm.RealmResults;

/**
 * Created by zoulu on 16/11/30.
 * RealmUtil工具类
 */

public class RealmUtil {

    /**
     * 获取所有的藏汉500句
     */
    public static RealmResults<Category> getAllCategory(){
        Realm realm = Realm.getDefaultInstance();
        RealmQuery<Category> query = realm.where(Category.class);
        return query.findAll();
    }

    /**
     * 根据名字模糊查询category
     */
    public static RealmResults<Category> getCategoryByName(String name){
        Realm realm = Realm.getDefaultInstance();
        RealmQuery<Category> query = realm.where(Category.class).contains("name",name);
        return query.findAll();
    }

    /**
     * 根据type获取Phrase的内容
     */
    public static RealmResults<Phrase> getPhraseByType(int type){
        Realm realm = Realm.getDefaultInstance();
        RealmQuery<Phrase> query = realm.where(Phrase.class).equalTo("type",type);
        return query.findAll();
    }

    /**
     *  根据uuid查找phrase内容
     */
    public static RealmResults<Phrase> getPhraseByCategoryUuid(int uuid){
        Realm realm = Realm.getDefaultInstance();
        RealmQuery<Phrase> query = realm.where(Phrase.class).equalTo("category.uuid",uuid);
        return query.findAll();
    }

    /**
     *  根据content模糊查找phrase内容
     */
    public static RealmResults<Phrase> getPhraseByName(String name){
        Realm realm = Realm.getDefaultInstance();
        RealmQuery<Phrase> query = realm.where(Phrase.class).contains("content",name);
        return query.findAll();
    }

    /**
     * copy文件到指定目录下
     */
    public static String copyBundledRealmFile(Activity activity, InputStream inputStream, String outFileName) {
        try {
            File file = new File(activity.getFilesDir(), outFileName);
            FileOutputStream outputStream = new FileOutputStream(file);
            byte[] buf = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buf)) > 0) {
                outputStream.write(buf, 0, bytesRead);
            }
            outputStream.close();
            return file.getAbsolutePath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
